package com.tajiang.business.businesscount;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tajiang.business.R;
import com.tajiang.business.businesscount.store.GoodsGovernActivity;
import com.tajiang.business.businesscount.store.StoreNoticeActivity;
import com.tajiang.business.businesscount.wallet.WalletMenuActivity;
import com.tajiang.business.common.application.TJApp;
import com.tajiang.business.common.dialog.DialogWithTwoButton;
import com.tajiang.business.common.fragment.BaseFragment;
import com.tajiang.business.common.utils.CashUtils;
import com.tajiang.business.common.utils.CommandTools;
import com.tajiang.business.common.utils.PostDataTools;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.common.utils.UserUtils;
import com.tajiang.business.common.widget.FlowLayout;

import java.io.ByteArrayOutputStream;
import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 *营业统计
 */
public class BusinessCountMenuFragment extends BaseFragment {

    @BindView(R.id.fragment_business_count)
    LinearLayout layout;

    @BindView(R.id.business_count_menu_icon)
    ImageView icon;

    @BindView(R.id.business_count_menu_name)
    TextView tvName;

    @BindView(R.id.business_count_menu_today_order)
    TextView tvTodayOrder;

    @BindView(R.id.business_count_menu_today_fee)
    TextView tvTodayFee;

    @BindView(R.id.business_count_menu_total_fee)
    TextView tvTotalFee;

    @BindView(R.id.business_count_menu_balance)
    TextView tvBalance;

    @BindView(R.id.business_count_menu_service)
    TextView tvPhone;

    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;
    private Bitmap bitmap;

    @Override
    protected void initTopBar() {

        setTitle("营业统计");
    }

    @Override
    protected void initLayout() {

        setContentView(R.layout.fragment_business_count_menu);
    }

    public void onResume(){
        super.onResume();

        PostDataTools.shop_info(getActivity(), new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                tvName.setText(UserUtils.mBusinessAccountInfo.getShopName());

                tvTodayOrder.setText(UserUtils.mBusinessAccountInfo.getTodayOrder() + "");
                tvTodayFee.setText(CashUtils.changeF2Y(UserUtils.mBusinessAccountInfo.getTodayMoney(), 0));
                tvTotalFee.setText(CashUtils.changeF2Y(UserUtils.mBusinessAccountInfo.getAllMoney(), 0));

                tvBalance.setText(CashUtils.changeF2Y(UserUtils.mBusinessAccountInfo.getBalance(), 0));

                TJApp.getImageLoader().displayImage(UserUtils.mBusinessAccountInfo.getAvatar(), icon);
            }
        });
    }

    @Override
    protected void initData() {

        tvPhone.setText(UserUtils.mUser.getCustomPhone());
    }

    //我的钱包
    @OnClick(R.id.business_count_menu_layout_wallet)
    public void wallet(){

        Intent intent = new Intent(getActivity(), WalletMenuActivity.class);
        startActivity(intent);
    }

    //菜品管理
    @OnClick(R.id.business_count_menu_layout_dishes)
    public void dishes(){

        Intent intent = new Intent(getActivity(), GoodsGovernActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.business_count_menu_layout_store)
    public void store(){

        Intent intent = new Intent(getActivity(), StoreNoticeActivity.class);
        intent.putExtra("notice", UserUtils.mBusinessAccountInfo.getNotice());
        startActivity(intent);
    }

    @OnClick(R.id.business_count_menu_layout_service)
    public void service(){

        final String phone = UserUtils.mUser.getCustomPhone();
        DialogWithTwoButton.showDialog(getActivity(), "取消", "确认", "拨打客服电话: " + phone, new DialogWithTwoButton.DialogCallback() {

            @Override
            public void callback(int position) {

                if(position == 1){

                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * resultCode == Activity.RESULT_CANCELED
         * 按返回键，退出拍照
         */
        if (resultCode != Activity.RESULT_CANCELED) {
            if (requestCode == PHOTO_REQUEST_GALLERY) {
                if (data != null) {
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    crop(uri);
                }

            } else if (requestCode == PHOTO_REQUEST_CAMERA) {
                if (CommandTools.hasSdcard()) {
                    tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
                    crop(Uri.fromFile(tempFile));

                } else {
                    ToastUtils.showShort("未找到存储卡，无法存储照片！");
                }

            } else if (requestCode == PHOTO_REQUEST_CUT) {

                try {
                    bitmap = data.getParcelableExtra("data");
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

                    PostDataTools.user_avatar(CommandTools.saveBitmap(bitmap).getPath(), new PostDataTools.DataCallback() {

                        @Override
                        public void callback(boolean flag, String message, Object object) {

                            if(flag){
                                icon.setImageBitmap(bitmap);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    @OnClick(R.id.business_count_menu_icon_layout)
    public void takephoto(){

        new PopupWindows(getActivity(), layout);
    }

    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent) {

            super(mContext);

            View view = View.inflate(mContext, R.layout.item_popupwindows, null);

            final LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
            getBackground().setAlpha(80);
            setAnimationStyle(R.style.AnimationFade);
            setWidth(FlowLayout.LayoutParams.MATCH_PARENT);
            setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
            setOutsideTouchable(false);
            setFocusable(false);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.layout_pop_window);
            Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);

            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    ll_popup.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out));
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    // 激活系统图库，选择一张图片
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    dismiss();
                }
            });
            bt1.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {

                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (CommandTools.hasSdcard()) {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                    }
                    startActivityForResult(intent, PHOTO_REQUEST_CAMERA);

                    dismiss();
                }
            });

            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }

    /**
     * 剪切图片
     *
     * @function:
     * @author:Jerry
     * @date:2013-12-30
     * @param uri
     */
    private void crop(Uri uri) {

        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

}
